import redis

from util.config_center import ConfigCenter


class RedisPoolConnect:
    """redis连接池"""
    def __init__(self, db_num=0):
        config = ConfigCenter.get_redis_config(db_num)
        # 新建redis连接池，redis读取的值默认为二进制形式, decode_responses对查询的值进行解码
        self.pool = redis.ConnectionPool(**config, decode_responses=True, max_connections=100)

    def create_connect(self):
        """从连接池获取连接"""
        return redis.Redis(connection_pool=self.pool)

    def set_key_value(self, key, value):
        """
        设置指定键的值
        :param key:键
        :param value:值
        """
        connect = self.create_connect()
        connect.set(key, value, ex=24 * 60 * 60)
        connect.close()

    def find_key_value(self, key):
        """
        查找键的值
        :param key: 键
        :return: 值
        """
        connect = self.create_connect()
        value = connect.get(key)
        connect.close()
        return value
